#!/usr/bin/python

import glob
import commands
import os

LSSCSI_CMD = '/usr/bin/lsscsi'
SCSIID_CMD = '/sbin/scsi_id'
MULTIPATH_CMD = '/sbin/multipath'

g_uuid = {}

def __getUUID(dev):

    if not g_uuid.has_key(dev):

        cmd = SCSIID_CMD + ' -gus /block/' + dev
        uuid = commands.getoutput(cmd)

        g_uuid[dev] = uuid

    return g_uuid[dev]

def DoDevHash():
    devs = {}
    for sddev in glob.glob('/dev/sd*'):
        dev = sddev.split('/')[-1]
        
        uuid = __getUUID(dev)

        if devs.has_key(uuid):
            devs[uuid] = '%s %s' % (devs[uuid], dev)
        else:
            devs[uuid] = dev

    return devs

def DoHTLHash():
    htls = {}

    for line in commands.getoutput(LSSCSI_CMD).split('\n'):
        fields = line.split()
        sddev = fields[-1]
        dev = sddev.split('/')[-1]

        uuid = __getUUID(dev)

        htl = fields[0]
        fields = htl.split(':')
        htl = '%s:%s:%s' % (fields[0], fields[2], fields[3])

        htls[htl] = uuid

    return htls

def DoMpathHash():
    mpaths = {}
    cmd = MULTIPATH_CMD + ' -ll |grep ^mpath'
    for line in commands.getoutput(cmd).split('\n'):
        fields = line.split()
        mpath = fields[0]
        uuid = fields[1]
        uuid = uuid[1:-1]

        mpaths[uuid] = mpath

    return mpaths

def ReadDevtable():
    filename = '/home/lunmgr/lunmgr.devtable'
    mount_pts = {}
    for line in open(filename):
        fields = line.rstrip().split()
        uuid = fields[0]
        
        mount_pt = fields[-2]
        name = fields[-1]

        if mount_pt != 'NONE':
            mount_pts[mount_pt + '/' + name] = uuid

    return mount_pts
        

